package ants

import (
	"log"
	"runtime"
	"time"
)

type goWorker struct {
	// 该worker在哪个协程池里面工作
	pool *Pool

	// 执行的代码
	task chan func()

	// 每次把worker重新放进队列的时候的时间
	recycleTime time.Time
}

func (w *goWorker) run() {
	w.pool.incRunning()
	go func() {

		defer func() {
			w.pool.decRunning()
			w.pool.workerCache.Put(w)

			if p := recover(); p != nil {
				if ph := w.pool.options.PanicHandler; ph != nil {
					ph(p)
				} else {
					log.Printf("worker exits from a panic: %v\n", p)
					var buf [4096]byte
					n := runtime.Stack(buf[:], false)
					log.Printf("worker exits from panic: %s\n", string(buf[:n]))
				}
			}
		}()

		for f := range w.task {
			if f == nil {
				return
			}
			f()
			if ok := w.pool.revertWorker(w); !ok {
				return
			}
		}
	}()
}
